<template>
  <div class="login-container">
    <Card style="width:400px" :padding="20">
      <div
        slot="title"
        style="display: flex;justify-content: space-between;align-items: center;">
        <span style="font-weight: bolder;">普通用户注册</span>
        <span>
          已有账号？
          <Button type="warning" to="/login">登录</Button>
        </span>
      </div>
      <div style="text-align:center">
        <Form
          ref="formValidate"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="80"
          label-position="left">
          <FormItem label="姓名" prop="name">
            <Input v-model="formValidate.name" placeholder="请输入你的用户名" />
          </FormItem>
          <FormItem label="密码" prop="password">
            <Input
              type="password"
              v-model="formValidate.password"
              placeholder="请输入你的密码" />
          </FormItem>
          <FormItem label="确认密码" prop="passwordCheak">
            <Input
              type="password"
              v-model="formValidate.passwordCheak"
              placeholder="请重复输入你的密码" />
          </FormItem>
          <FormItem label="性别" prop="sex" :required="true" style="text-align: justify;">
            <RadioGroup v-model="formValidate.sex">
              <Radio label="1">男</Radio>
              <Radio label="0">女</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="学院" prop="college" :required="true">
            <Select v-model="formValidate.college" @on-change="getThisMajor" placeholder="请选择你的学院">
              <Option
                v-for="item in College"
                :value="''+item.colle_id"
                :key="item.colle_id">{{ item.colle_name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="专业" prop="major" :required="true">
            <Select v-model="formValidate.major" :disabled="isDisabled" placeholder="请选择你的专业">
              <Option
                v-for="item in Major"
                :value="''+item.major_id"
                :key="item.major_id">{{ item.major_name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="邮箱" prop="mail">
            <Input v-model="formValidate.mail" placeholder="请输入你的邮箱号码" />
          </FormItem>
          <FormItem label="电话" prop="phone">
            <Input v-model="formValidate.phone" placeholder="请输入你的电话号码" />
          </FormItem>
          <FormItem label="验证码" prop="captcha">
            <Input
              v-model="formValidate.captcha"
              placeholder="请输入验证码"
              clearable
              style="width: 120px;float:left;" />
            <span>
              <img
                :src="captchaURL"
                @click="randNum = Math.random()"
                title="点击刷新" />
            </span>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSubmit('formValidate')">注册</Button>
            <Button
              @click="handleReset('formValidate')"
              style="margin-left: 8px">重置</Button>
          </FormItem>
        </Form>
      </div>
    </Card>
  </div>
</template>
<script>
  export default {
    name: "Register",
    data () {
      const validatePass = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入您的密码"));
        } else {
          if (this.formValidate.passwordCheak !== "") {
            // 对第二个密码框单独验证
            this.$refs.formValidate.validateField("passwordCheak");
          }
          callback();
        }
      };
      const validatePassCheck = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请重新输入您的密码"));
        } else if (value !== this.formValidate.password) {
          callback(new Error("两个输入密码不匹配!"));
        } else {
          callback();
        }
      };
      return {
        College: [],
        Major: [],
        isDisabled: true,
        randNum: Math.random(), //为刷新验证码图片地址准备的随机数字
        formValidate: {
          name: "",
          password: "",
          passwordCheak: "",
          captcha: "",
          sex: "1",
          college: "",
          major: "",
          mail: "",
          phone: ""
        },
        ruleValidate: {
          name: [
            {
              required: true,
              message: "请填写你的用户名",
              trigger: "blur"
            }
          ],
          password: [
            { required: true, validator: validatePass, trigger: "blur" }
          ],
          passwordCheak: [
            { required: true, validator: validatePassCheck, trigger: "blur" }
          ],
          captcha: [
            {
              required: true,
              message: "请填写验证码",
              trigger: "blur"
            }
          ],
          sex: [{ required: true, message: "请选择你的性别", trigger: "change" }],
          college: [
            { required: true, message: "请选择你的学院", trigger: "change" }
          ],
          major: [
            { required: true, message: "请选择你的专业", trigger: "change" }
          ],
          mail: [
            { required: true, message: "邮箱不能为空", trigger: "blur" },
            { type: "email", message: "邮箱格式不正确", trigger: "change" }
          ],
          phone: [
            {
              validator (rule, value) {
                if (value.trim() == "") {
                  return new Error("电话号码不能为空！");
                } else {
                  let reg = new RegExp(/^1[3456789]\d{9}$/);
                  if (reg.test(value)) {
                    return true;
                  } else {
                    return new Error("请输入正确的手机号码！");
                  }
                }
              },
              type: "number",
              required: true
            }
          ]
        }
      };
    },
    computed: {
      //计算属性：返回验证码图片的地址
      //例如：<img src="http://127.0.0.1:8080/captcha/register?0.135123">
      captchaURL () {
        return this.$axios.defaults.baseURL + "/captcha/register?" + this.randNum;
      }
    },
    methods: {
      //提交注册
      handleSubmit (name) {
        this.$refs[name].validate(valid => {
          console.log(this.formValidate);
          if (valid) {
            this.randNum = Math.random();
            const params = this.$qs.stringify({
              name: this.formValidate.name,
              password: this.formValidate.password,
              passwordCheak: this.formValidate.passwordCheak,
              captcha: this.formValidate.captcha,
              sex: this.formValidate.sex,
              college: this.formValidate.college,
              major: this.formValidate.major,
              mail: this.formValidate.mail,
              phone: this.formValidate.phone
            });

            this.$axios
              .post("/user/register", params)
              .then(res => {
                console.log(res.data);
                if (res.data.code == 200) {
                  //注册成功
                  this.$Message.success({
                    content: "注册成功！请登录！",
                    duration: 1,
                    onClose: () => {
                      //跳转到主页
                      this.$router.push("/login");
                    }
                  });

                } else if (res.data.code == 410) {
                  this.$Message.error("用户名已被占用！");
                } else if (res.data.code == 412) {
                  this.$Message.error("验证码错误！");
                } else {
                  this.$Message.error("注册失败！请重试！");
                }
              })
              .catch(err => {
                this.$Message.error("服务器错误！请稍后重试！");
                console.error(err);
              });
          } else {
            this.$Message.error("请填写完整！");
          }
        });
      },
      //按下重置
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      //选择学院
      getThisMajor () {
        this.$axios
          .get(`/user/getMajor?college_id=${this.formValidate.college}`)
          .then(res => {
            this.isDisabled = false;
            this.Major = res.data.data;
          })
          .catch(err => {
            console.error(err);
          });
      }
    },
    mounted () {
      this.$axios
        .get("/user/getCollege")
        .then(res => {
          this.College = res.data.data;
        })
        .catch(err => {
          console.error(err);
        });
    }
  };
</script>
<style scoped>
  .login-container {
    background-image: url(../assets/login-bg.jpg);
    height: 100vh;
    position: relative;
  }
  .ivu-card {
    position: absolute;
    top: 15%;
    left: 60%;
  }
</style>
